import dayjs from "dayjs";
import { ref, reactive, h, onMounted, toRaw, nextTick } from "vue";
import { extractFields, cloneDeep } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import { hasAuth } from "@/router/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form/index.vue";
import detailForm from "../../showDetail.vue";
import { dealStoreList } from "../../list";
import Sortable from "sortablejs";
import { getStoreSimplePage } from "@/api/basicArchives/storeManagement";
import { DictTag } from "@/components/common/DictTag";
import {
  getRulePage,
  ruleAdd,
  ruleUpdate,
  ruleDelete
} from "@/api/basicArchives/allocateRule";
import { getDepositoryPage } from "@/api/basicArchives/warehouseManagement";

export function useSplitOrder() {
  const form = reactive({
    ruleType: 2 // 1库存权限 2拆单配置
  });

  const loading = ref(false);
  const dataList = ref([]);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      label: "配货规则名称",
      prop: "ruleName"
    },
    {
      label: "佳叽仓库",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <>
          {row.priorityList.map(i => (
            <el-tag
              style={{ marginRight: "5px" }}
              type="primary"
              effect="plain"
            >
              {i.depositoryName}
            </el-tag>
          ))}
        </>
      )
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <>
          <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
        </>
      )
    },
    {
      label: "门店",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <>
          <el-button
            v-show={row.storeList.length > 0}
            text
            type="primary"
            size="small"
            onClick={() => handleDetail(row.storeList)}
          >
            查看
          </el-button>
        </>
      )
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  const handleDetail = storeList => {
    let title = "门店查看";
    addDialog({
      title,
      props: {
        formInline: {
          idList: storeList.map(v => v.id) || [],
          collapseList: dataAll.map(v => v.id) || [],
          storeOptions: dataAll || []
        }
      },
      width: "850px",
      fullscreenIcon: true,
      closeOnClickModal: false,
      sureBtnLoading: true,
      contentRenderer: () => h(detailForm),
      beforeSure: done => {
        done();
      }
    });
  };

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    const { data } = await getRulePage(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const formRef = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (title == "新增") {
      depositoryAll = JSON.parse(localStorage.getItem("depositoryAll"));
    }
    dataAll = JSON.parse(localStorage.getItem("dataAll"));

    if (title !== "新增") {
      depositoryAll = cloneDeep(row?.priorityList);
    }

    addDialog({
      title: `${title}配货规则`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          ruleType: row?.ruleType ?? 2,
          ruleName: row?.ruleName ?? undefined,
          priorityList: row?.priorityList ?? [],
          goodsType: row?.goodsType ?? undefined,
          storeIds: row?.storeIds ?? [],
          storeList: row?.storeList ?? [],
          dataAll,
          depositoryAll,
          columnsDetail
        }
      },
      width: "1000px",
      sureBtnLoading: true,
      fullscreenIcon: true,
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        let sortAll = [];
        if (options.props.formInline.depositoryAll?.length > 0) {
          options.props.formInline.depositoryAll.forEach((item, i) => {
            item.priority = i + 1;
          });

          sortAll = options.props.formInline.depositoryAll;

          options.props.formInline.priorityList = extractFields(
            sortAll,
            "depositoryId",
            "depositoryName",
            "priority"
          );
        }

        const FormRef = formRef.value.getRef();

        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            delete curData.dataAll;
            delete curData.depositoryAll;
            delete curData.columnsDetail;

            // console.log("curData", curData);
            if (title === "新增") {
              // 表单规则校验通过
              // 实际开发先调用新增接口，再进行下面操作
              const { code } = await ruleAdd(curData);
              if (code == 200) {
                chores();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await ruleUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function handleDelete(row) {
    const res = await ruleDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  let dataAll = reactive([]);
  const params = {
    pageNum: 1,
    pageSize: 999
  };

  async function storeList() {
    const { data } = await getStoreSimplePage(params);
    dataAll = dealStoreList(data.records);
    localStorage.setItem("dataAll", JSON.stringify(dataAll));
  }

  let depositoryAll = reactive([]);

  async function depositoryList() {
    const { data } = await getDepositoryPage(params);
    data.records.forEach((item, i) => {
      item.depositoryId = item.id;
      item.priority = i + 1;
    });
    depositoryAll = data.records;
    localStorage.setItem("depositoryAll", JSON.stringify(depositoryAll));
  }

  const rowDrop = (event: { preventDefault: () => void }) => {
    event.preventDefault();
    nextTick(() => {
      const wrapper: HTMLElement = document.querySelector(
        ".drag-table .el-table__body-wrapper tbody"
      );
      Sortable.create(wrapper, {
        animation: 300,
        handle: ".drag-btn",
        onEnd: ({ newIndex, oldIndex }) => {
          const currentRow = depositoryAll.splice(oldIndex, 1)[0];
          depositoryAll.splice(newIndex, 0, currentRow);
        }
      });
    });
  };

  const columnsDetail: TableColumnList = [
    {
      label: "优先级",
      prop: "priority",
      cellRenderer: ({ row }) => (
        <div class="flex items-center">
          <iconify-icon-online
            icon="icon-park-outline:drag"
            class="drag-btn cursor-grab"
            onMouseenter={(event: { preventDefault: () => void }) =>
              rowDrop(event)
            }
          />
          <p class="ml-[16px]">{row.priority}</p>
        </div>
      )
    },
    {
      label: "佳叽仓库",
      prop: "depositoryName"
    }
  ];

  onMounted(() => {
    onSearch();
    storeList();
    depositoryList();
  });

  return {
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    hasAuth,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    useRenderIcon,
    handleDelete
  };
}
